package com.gome.ss.flowcrawl.extractor;

import java.io.IOException;
import java.util.Map;

import org.apache.log4j.Logger;
import org.elasticsearch.action.admin.cluster.health.ClusterHealthRequest;
import org.elasticsearch.action.admin.indices.create.CreateIndexRequest;
import org.elasticsearch.action.admin.indices.mapping.put.PutMappingRequest;
import org.elasticsearch.action.admin.indices.mapping.put.PutMappingResponse;
import org.elasticsearch.client.Client;
import org.elasticsearch.client.Requests;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.ImmutableSettings;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.InetSocketTransportAddress;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentFactory;

import com.gome.spiderkit.client.Utils;
import com.gome.ss.common.AppConfiguer;
import com.sun.jersey.test.framework.spi.client.ClientFactory;

public class ElasticsearchClientFactory {
	private static Logger logger = Logger.getLogger(ElasticsearchClientFactory.class);
    private static volatile Client client=null;
    
    public static Client getClient(){
        if( null==client ){
            synchronized(ElasticsearchClientFactory.class){
                if(null==client){
                    Settings settings = ImmutableSettings.settingsBuilder().put("cluster.name", "gome_spider").build();
                    client = new TransportClient(settings)
                    .addTransportAddresses(new InetSocketTransportAddress(AppConfiguer.getStringByKey("ESServerIP"),
                    		AppConfiguer.getIntByKey("ESServerPort")));
                    return client;
                }else{
                    return client;
                }   
            }
        }else{
            return client; 
        }
    }
    
    /**
    * 创建mapping
    * @param client es client
    * @param indices 索引名称
    * @param mappingType 索引类型
    * @throws Exception
    */
    public static void createMapping(Client client, String indices,String mappingType) {
        client.admin().indices().prepareCreate(indices).execute().actionGet();
		try {
			XContentBuilder builder = XContentFactory.jsonBuilder()
			.startObject()
		        .startObject("properties")
			        .startObject("id").field("type", "string").field("index","not_analyzed").endObject()
			        .startObject("crawlName").field("type", "string").field("index","not_analyzed").endObject()
			        .startObject("keyWord").field("type", "string").field("index","analyzed").field("analyzer","whitespace").endObject()
			        .startObject("date").field("type", "date").field("format","yyyy-MM-dd HH:mm:ss:SSS").endObject()
			        .startObject("storageDate").field("type", "date").field("format","yyyy-MM-dd HH:mm:ss:SSS").endObject()
			        .startObject("extractDataFacetKeyFields").field("type", "string").field("index","not_analyzed").endObject()
		        .endObject()
			.endObject();
	        
			System.out.println(builder.string());
			
	        PutMappingRequest mapping = Requests.putMappingRequest(indices).type(mappingType).source(builder);
	        PutMappingResponse response = client.admin().indices().putMapping(mapping).actionGet();
	        
		} catch (Exception e) {
			logger.error(Utils.getTrace(e));
		}
    }
	
	public static void appendNotAnalyzedMappingField(Client client, String indices, String mappingType, String field) throws Exception {
		XContentBuilder builder = XContentFactory.jsonBuilder()
		.startObject()
	        .startObject("properties")
		        .startObject(field).field("type", "string").field("index","not_analyzed").endObject()
	        .endObject()
		.endObject();
        
		logger.info("Append not analyzed mapping field : " + indices + " " + mappingType + " " + builder.string());
		
        PutMappingRequest mapping = Requests.putMappingRequest(indices).type(mappingType).source(builder);
        PutMappingResponse response = client.admin().indices().putMapping(mapping).actionGet();
	}
}
